package com.fy.fyspace.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.fyspace.common.manager.CosManager;
import com.fy.fyspace.common.result.R;
import com.fy.fyspace.ex.handler.ExHandler;
import com.fy.fyspace.mapper.AipictureMapper;
import com.fy.fyspace.mapper.PictureMapper;
import com.fy.fyspace.mapper.SpaceMapper;
import com.fy.fyspace.model.entity.Picture;
import com.fy.fyspace.model.entity.Space;
import com.fy.fyspace.model.enums.picture.PictureDeleteStatusEnum;
import com.fy.fyspace.model.enums.picture.PictureReviewStatusEnum;
import com.fy.fyspace.model.vo.picture.PictureVO;
import com.fy.fyspace.model.vo.picture.RejectPicVO;
import com.fy.fyspace.model.vo.picture.ReviewPictureVO;
import com.fy.fyspace.service.SpaceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.fy.fyspace.common.result.R.ok;

/**
 * @author fwq
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2024-12-20 11:49:50
 */
@Service
@Slf4j
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space> implements SpaceService {

    @Resource
    private PictureMapper pictureMapper;

    @Resource
    private CosManager cosManager;

    @Resource
    private AipictureMapper aipictureMapper;

    /**
     * 获取当前用户待审核的图片列表
     *
     * @param pageNo
     * @param pageSize
     * @param id
     * @return
     */
    @Override
    public R getReviewPictures(Integer pageNo, Integer pageSize, Integer reviewStatus, Long id) {
        // 构建查询条件
        LambdaQueryWrapper<Picture> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Picture::getUserId, id)
                .eq(Picture::getIsDelete, PictureDeleteStatusEnum.NOT_DELETE.getValue())
                .eq(Picture::getReviewStatus, reviewStatus)
                .orderByDesc(Picture::getCreateTime);

        // 执行分页查询
        PageHelper.startPage(pageNo, pageSize);
        List<Picture> pictureList = pictureMapper.selectList(queryWrapper);
        PageInfo<Picture> pageInfo = new PageInfo<>(pictureList);
        log.info("从数据库获取个人空间图片列表成功: userId={}, total={}",
                id, pageInfo.getTotal());

        Map<String, Object> result = new HashMap<>();

        if (PictureReviewStatusEnum.REJECT.getValue() == reviewStatus) {
            List<RejectPicVO> pictureVOList = pictureList.stream()
                    .map(RejectPicVO::objToVo)
                    .collect(Collectors.toList());
            result.put("records", pictureVOList);
        } else if (PictureReviewStatusEnum.REVIEWING.getValue() == reviewStatus) {
            List<PictureVO> pictureVOList = pictureList.stream()
                    .map(PictureVO::objToVo)
                    .collect(Collectors.toList());
            result.put("records", pictureVOList);
        }

        result.put("total", pageInfo.getTotal());
        result.put("size", pageInfo.getPageSize());
        result.put("current", pageInfo.getPageNum());
        result.put("pages", pageInfo.getPages());
        return ok(result);
    }

    /**
     * 批量删除被反驳照片
     *
     * @param pictureIds 图片ID列表
     * @return 操作结果
     */
    @Override
    @Transactional
    public R batchDeleteRejectPictures(List<Long> pictureIds) {
        log.info("开始批量删除被反驳照片: pictureIds={}", pictureIds);

        ExHandler.throwIf(pictureIds == null || pictureIds.isEmpty(), "请选择要删除的图片");

        // todo 数据库的删除字段更新失败，原因未知
        pictureIds.forEach(pictureId -> {
            Picture picture = pictureMapper.selectById(pictureId);
            ExHandler.throwIf(picture == null, "图片不存在");

            // 更新删除状态
            picture.setIsDelete(PictureDeleteStatusEnum.IS_DELETE.getValue());
            pictureMapper.updateById(picture);

            // 删除COS中的文件
            cosManager.deleteObject(picture.getUrl());
            if (picture.getThumbnailUrl() != null) {
                cosManager.deleteObject(picture.getThumbnailUrl());
            }

            log.info("删除被反驳照片成功: pictureId={}", pictureId);
        });

        return ok();
    }

    /**
     * 获取AI图列表
     *
     * @param pageNo     页码
     * @param pageSize   每页数量
     * @param searchText 搜索关键词
     * @param userId     用户ID
     * @return 分页结果
     */
    @Override
    public R getAiPictureList(Integer pageNo, Integer pageSize, String searchText, Long userId) {
        // 设置默认值
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 30 : pageSize;

//        // 构建查询条件 todo
//        LambdaQueryWrapper<Aipicture> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Aipicture::getUserId, userId)
//                .eq(Aipicture::getIsDelete, PictureDeleteStatusEnum.NOT_DELETE.getValue())
//                .eq(Aipicture:, true) // AI生成的图片
//                .orderByDesc(Picture::getCreateTime);
//
//        // 如果有搜索关键词，添加搜索条件
//        if (StrUtil.isNotBlank(searchText)) { // 模糊搜索
//            queryWrapper.and(wrapper -> wrapper
//                    .like(Picture::getName, searchText)  // 名称
//                    .or()  // 介绍
//                    .like(Picture::getIntroduction, searchText) // 标签
//                    .or()
//                    .like(Picture::getName, searchText));
//        }
//
//        // 执行分页查询
//        PageHelper.startPage(pageNo, pageSize);
//        List<Picture> pictureList = pictureMapper.selectList(queryWrapper);
//        PageInfo<Picture> pageInfo = new PageInfo<>(pictureList);
//
//        log.info("获取AI图列表成功: userId={}, total={}", userId, pageInfo.getTotal());
//
//        // 转换为VO对象
//        List<PictureVO> pictureVOList = pictureList.stream()
//                .map(PictureVO::objToVo)
//                .collect(Collectors.toList());
//
//        // 构建返回结果
//        Map<String, Object> result = new HashMap<>();
//        result.put("records", pictureVOList);
//        result.put("total", pageInfo.getTotal());
//        result.put("size", pageInfo.getPageSize());
//        result.put("current", pageInfo.getPageNum());
//        result.put("pages", pageInfo.getPages());
//
//        return ok(result);
        return ok();
    }

    /**
     * 获取个人空间图片列表
     * @param page 页码
     * @param pageSize 每页数量
     * @param tags 标签
     * @param description 描述
     * @param category 分类
     * @param reviewStatus 审核状态
     * @param userId 用户ID
     * @return
     */
    @Override
    public R getSpacePictureList(Integer page, Integer pageSize, String tags, String description, String category, Integer reviewStatus, Long userId) {
        // 构建查询条件
        LambdaQueryWrapper<Picture> queryWrapper = new LambdaQueryWrapper<>();
        if (userId != null) {
            queryWrapper.eq(Picture::getUserId, userId);
        }
        queryWrapper.eq(Picture::getIsDelete, PictureDeleteStatusEnum.NOT_DELETE.getValue());
        if (reviewStatus != null) {
            queryWrapper.eq(Picture::getReviewStatus, reviewStatus);
        }
        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.eq(Picture::getCategory, category);
        }
        if (description != null && !description.trim().isEmpty()) {
            queryWrapper.eq(Picture::getIntroduction, description);
        }
        if (tags != null && !tags.trim().isEmpty()) {
            String[] tagArray = tags.split(",");
            for (String tag : tagArray) {
                tag = tag.trim();
                if (!tag.isEmpty()) {
                    queryWrapper.like(Picture::getTags, tag);
                }
            }
        }
        queryWrapper.orderByDesc(Picture::getCreateTime);

        // 分页查询
        PageHelper.startPage(page == null ? 1 : page, pageSize == null ? 30 : pageSize);
        List<Picture> pictureList = pictureMapper.selectList(queryWrapper);
        PageInfo<Picture> pageInfo = new PageInfo<>(pictureList);

        Map<String, Object> result = new HashMap<>();
        List<ReviewPictureVO> pictureVOList = pictureList.stream()
                .map(p -> {
                    ReviewPictureVO vo = BeanUtil.copyProperties(p, ReviewPictureVO.class);
                    vo.setId(p.getId() != null ? String.valueOf(p.getId()) : null);
                    return vo;
                })
                .collect(Collectors.toList());
        result.put("records", pictureVOList);
        result.put("total", pageInfo.getTotal());
        result.put("size", pageInfo.getPageSize());
        result.put("current", pageInfo.getPageNum());
        result.put("pages", pageInfo.getPages());
        return ok(result);
    }
}
